﻿using System;
using System.Configuration; // 需要添加对System.Configuration的引用
using System.Windows.Forms;
using System.Security.Cryptography; // 引入加密依赖
namespace WinFormswork2
{
    public partial class LoginForm : Form
    {
        private string userFilePath;

        public LoginForm()
        {
            InitializeComponent();

            userFilePath = ConfigurationManager.AppSettings["UserFilePath"];
        }

        private void btn_Login_Click(object sender, EventArgs e)
        {
            string username = username_textBox.Text;
            string password = password_textBox.Text;

            if (ValidateCredentials(username, password))
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("用户名或密码错误！", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool ValidateCredentials(string username, string password)
        {

            string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string filePath = Path.Combine(currentDirectory, userFilePath);
            string hashedPassword = GetSha256Hash(password); // 加密输入的密码

            try
            {
                var lines = System.IO.File.ReadAllLines(filePath);
                foreach (var line in lines)
                {
                    var parts = line.Split(',');
                    if (parts.Length == 2)
                    {
                        if (parts[0] == username && parts[1] == hashedPassword)
                        {
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"读取用户信息失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return false;
        }

        // 登陆逻辑
        private void btn_register_Click(object sender, EventArgs e)
        {
            string username = username_textBox.Text;
            string password = password_textBox.Text;

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("用户名和密码不能为空！", "注册失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (IsUsernameExists(username))
            {
                MessageBox.Show("该用户名已被注册，请使用其他用户名！", "注册失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                RegisterNewUser(username, password);
            }
        }

        private bool IsUsernameExists(string username)
        {
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, userFilePath);
            try
            {
                var lines = System.IO.File.ReadAllLines(filePath);
                foreach (var line in lines)
                {
                    var parts = line.Split(',');
                    if (parts.Length == 2 && parts[0] == username)
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法读取用户数据: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return false;
        }

        private void RegisterNewUser(string username, string password)
        {
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, userFilePath);
            string hashedPassword = GetSha256Hash(password); // 加密密码
            try
            {
                using (var sw = System.IO.File.AppendText(filePath))
                {
                    sw.WriteLine($"{username},{hashedPassword}");
                }
                MessageBox.Show("注册成功，请登录。", "注册成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法写入用户数据: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // SHA256 哈希算法 封装加密方法
        private string GetSha256Hash(string input)
        {
            using (SHA256 sha256Hash = SHA256.Create())
            {
                // ComputeHash - 返回字节数组
                byte[] bytes = sha256Hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(input));

                // 将字节数组转换成十六进制的字符串
                System.Text.StringBuilder builder = new System.Text.StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    builder.Append(bytes[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }

    }
}